/**
 * 同步任务监控服务
 * 监控运行中的同步任务并将其显示在Dynamic Island中
 * 与useSyncTaskProgress Hook配合使用，提供全局任务监控能力
 */

import { SyncTaskProgressHook } from '../hooks/useSyncTaskProgress';
import { syncApi } from './syncApi';

export interface SyncTaskStatus {
  id: number;
  taskId: number;
  taskName: string;
  status: string;
  progress: number;
  totalRecords: number;
  processedRecords: number;
  successRecords: number;
  failedRecords: number;
  startedAt: string;
  estimatedTimeRemaining?: number;
  currentBatch?: number;
  totalBatches?: number;
}

/**
 * 同步任务监控服务类
 * 提供全局的同步任务监控功能
 */
class SyncTaskMonitorService {
  private syncProgressHook: SyncTaskProgressHook | null = null;
  private monitoringTasks: Map<number, string> = new Map(); // executionId -> notificationId
  private taskInfo: Map<number, { taskName: string; sourceType: string; targetType: string }> = new Map(); // executionId -> task info
  private pollingInterval: NodeJS.Timeout | null = null;
  private isPolling = false;

  /**
   * 初始化监控服务
   * @param progressHook 同步任务进度Hook实例
   */
  initialize(progressHook: SyncTaskProgressHook) {
    this.syncProgressHook = progressHook;
    console.log('🔧 SyncTaskMonitorService 已初始化');
  }

  /**
   * 更新Hook引用
   * @param progressHook 新的Hook实例
   */
  updateHooks(progressHook: SyncTaskProgressHook) {
    this.syncProgressHook = progressHook;
  }

  /**
   * 开始监控同步任务
   * @param executionId 执行记录ID
   * @param taskName 任务名称
   * @param sourceType 源数据类型
   * @param targetType 目标数据类型
   */
  startMonitoring(
    executionId: number,
    taskName: string,
    sourceType: string,
    targetType: string
  ): string | null {
    if (!this.syncProgressHook) {
      console.warn('⚠️ SyncTaskMonitorService 未初始化');
      return null;
    }

    // 检查是否已在监控
    if (this.monitoringTasks.has(executionId)) {
      console.warn(`任务执行 ${executionId} 已在监控中`);
      return this.monitoringTasks.get(executionId) || null;
    }

    try {
      // 启动Dynamic Island通知
      const notificationId = this.syncProgressHook.startSyncTask(
        taskName,
        sourceType,
        targetType
      );

      // 记录监控任务和任务信息
      this.monitoringTasks.set(executionId, notificationId);
      this.taskInfo.set(executionId, { taskName, sourceType, targetType });

      // 启动轮询（如果尚未启动）
      this.startPolling();


      return notificationId;
    } catch (error) {
      console.error('❌ 启动任务监控失败:', error);
      return null;
    }
  }

  /**
   * 停止监控指定任务
   * @param executionId 执行记录ID
   */
  stopMonitoring(executionId: number) {
    const notificationId = this.monitoringTasks.get(executionId);
    if (notificationId && this.syncProgressHook) {
      this.syncProgressHook.cancelSyncTask(notificationId, '监控已停止');
    }
    
    this.monitoringTasks.delete(executionId);
    
    // 如果没有监控任务了，停止轮询
    if (this.monitoringTasks.size === 0) {
      this.stopPolling();
    }
  }

  /**
   * 启动轮询
   */
  private startPolling() {
    if (this.isPolling) return;

    this.isPolling = true;
    this.pollingInterval = setInterval(() => {
      this.pollAllTasks();
    }, 2000); // 每2秒轮询一次


  }

  /**
   * 停止轮询
   */
  private stopPolling() {
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
      this.pollingInterval = null;
    }
    this.isPolling = false;

  }

  /**
   * 轮询所有监控中的任务
   */
  private async pollAllTasks() {
    if (this.monitoringTasks.size === 0) return;

    for (const executionId of this.monitoringTasks.keys()) {
      await this.updateTaskStatus(executionId);
    }
  }

  /**
   * 更新任务状态
   */
  private async updateTaskStatus(executionId: number) {
    if (!this.syncProgressHook) return;

    try {
      // 通过执行记录列表API获取特定执行记录
      const executionsResponse = await syncApi.getSyncExecutions({ page: 1, page_size: 100 });

      const execution = executionsResponse.items.find(e => e.id === executionId);

      if (!execution) {
        return;
      }


      const notificationId = this.monitoringTasks.get(executionId);
      if (!notificationId) {
        return;
      }

      // 确保进度是数字类型
      const progress = typeof execution.progress_percentage === 'string'
        ? parseFloat(execution.progress_percentage)
        : (execution.progress_percentage || 0);
      const processedRecords = execution.processed_records || 0;
      const totalRecords = execution.total_records || 0;

      // 根据进度确定当前阶段（简洁显示）
      let currentStage = '初始化';
      if (progress > 0 && progress < 20) {
        currentStage = '连接数据源';
      } else if (progress >= 20 && progress < 40) {
        currentStage = '读取数据';
      } else if (progress >= 40 && progress < 70) {
        currentStage = '处理数据';
      } else if (progress >= 70 && progress < 90) {
        currentStage = '写入数据';
      } else if (progress >= 90) {
        currentStage = '验证完成';
      }

      // 获取任务信息
      const taskInfo = this.taskInfo.get(executionId);

      // 更新进度
      this.syncProgressHook.updateSyncProgress(
        notificationId,
        progress,
        currentStage,
        processedRecords,
        totalRecords,
        {
          successRecords: execution.success_records || 0,
          failedRecords: execution.failed_records || 0,
          currentBatch: execution.current_batch || 0,
          totalBatches: execution.total_batches || 0,
          executionId: executionId,
          taskName: taskInfo?.taskName || '未知任务',
          sourceType: taskInfo?.sourceType || 'Unknown',
          targetType: taskInfo?.targetType || 'Unknown'
        }
      );

      // 检查任务是否完成（只处理真正的完成状态）
      const completedStatuses = ['success', 'failed', 'cancelled'];
      if (completedStatuses.includes(execution.status)) {
        const success = execution.status === 'success';



        const summary = success
          ? `同步完成：处理 ${processedRecords} 条记录，成功 ${execution.success_records || 0} 条`
          : `同步失败：已处理 ${processedRecords} 条记录`;

        this.syncProgressHook.completeSyncTask(
          notificationId,
          success,
          summary,
          {
            processedRecords,
            successRecords: execution.success_records || 0,
            failedRecords: execution.failed_records || 0,
            totalRecords,
            executionId: executionId
          }
        );

        // 移除监控和任务信息
        this.monitoringTasks.delete(executionId);
        this.taskInfo.delete(executionId);
      }

    } catch (error) {
      console.error('更新同步任务状态失败:', error);
      
      // 如果获取状态失败，标记任务为失败
      const notificationId = this.monitoringTasks.get(executionId);
      if (notificationId) {
        this.syncProgressHook.failSyncTask(notificationId, {
          message: '无法获取任务状态',
          code: 'STATUS_FETCH_FAILED',
          details: error
        });
        this.monitoringTasks.delete(executionId);
        this.taskInfo.delete(executionId);
      }
    }
  }

  /**
   * 清除所有监控任务
   */
  clearAllMonitoring() {
    if (this.syncProgressHook) {
      for (const notificationId of this.monitoringTasks.values()) {
        this.syncProgressHook.cancelSyncTask(notificationId, '监控服务已清理');
      }
    }
    
    this.monitoringTasks.clear();
    this.taskInfo.clear();
    this.stopPolling();

  }

  /**
   * 获取当前监控的任务数量
   */
  getMonitoringTaskCount(): number {
    return this.monitoringTasks.size;
  }

  /**
   * 检查是否正在监控指定任务
   */
  isMonitoring(executionId: number): boolean {
    return this.monitoringTasks.has(executionId);
  }

  /**
   * 获取所有监控中的任务ID
   */
  getMonitoringTaskIds(): number[] {
    return Array.from(this.monitoringTasks.keys());
  }
}

// 导出单例实例
export const syncTaskMonitor = new SyncTaskMonitorService();
